function out = get_subwindow(im, pos, sz, target_sz, target_hist, cos_window)

%sz = target_sz * (1+padding);

if isscalar(sz),  %square sub-window
    sz = [sz, sz];
end

xs = floor(pos(2)) + (1:sz(2)) - floor(sz(2)/2);
ys = floor(pos(1)) + (1:sz(1)) - floor(sz(1)/2);

%check for out-of-bounds coordinates, and set them to the values at
%the borders
xs(xs < 1) = 1;
ys(ys < 1) = 1;
xs(xs > size(im,2)) = size(im,2);
ys(ys > size(im,1)) = size(im,1);

level = 0;

%extract image
im_patch = im(ys, xs, :);
if(size(im_patch,3)==3)
    out(:,:,level+1) = single(rgb2gray(im_patch))/255 - 0.5;
else
    out(:,:,level+1) = single(im_patch)/255 - 0.5;
end
level = level + 1;

if ~isempty(target_hist)
    context_hist = get_context_hist(im, pos, target_sz, 2);
    out(:,:,level+1) = map_color_ratio(im_patch, target_hist, context_hist);
    level = level + 1;

    context_hist = get_context_hist(im, pos, target_sz, 3);
    out(:,:,level+1) = map_color_ratio(im_patch, target_hist, context_hist);
    level = level + 1;

    context_hist = get_context_hist(im, pos, target_sz, 4);
    out(:,:,level+1) = map_color_ratio(im_patch, target_hist, context_hist);
    
    %ratio_feature = out(:,:,2:4);
    %[mean(ratio_feature(:)) max(ratio_feature(:))]
end

if ~isempty(cos_window),
	out = bsxfun(@times, out, cos_window);
end

end

